from datetime import datetime

from Acquisition import aq_inner, aq_parent

from Products.Five.browser import BrowserView

from Products.CMFCore.utils import getToolByName
from my315ok.xtinfocontent.interfaces import Inavlink


import transaction





class View(BrowserView):
    """Migration View
    """

    def __call__(self):

        context = aq_inner(self.context)
        out = []
        self.total_tag_migrated = 0
        self.total_tag_deleted = 0
        
        dry_run = self.request.has_key("dry_run")
        
        # This is for testing only.
        # Do not use transactions during a test.
        test = self.request.has_key("test") 
        
        if not test:
            transaction.begin()
        
        catalog = getToolByName(context, 'portal_catalog')
        
        def log(msg):
            # encode string before sending it to external world 
            if isinstance(msg, unicode): 
                msg = msg.encode('utf-8')             
            context.plone_log(msg)
            out.append(msg)

        

        # Find content
#        import pdb
#        pdb.set_trace()
        brains = catalog(object_provides=Inavlink.__identifier__,ltag='')
        log("Found %s navlink content objects." % len(brains))

        
        


        # Recursively run through the comment tree and migrate all comments.
        for brain in brains:
            obj = brain.getObject()
            ltag = getattr( obj, 'ltag', None )
            
            if ltag == '':
#                import pdb
#                pdb.set_trace()
                

                oldtag = getattr( obj, 'tag', None )
                setattr(obj,'ltag',oldtag)
                obj.reindexObject()
  

       
        
        if dry_run and not test:
            transaction.abort()
            log("Dry run")
            log("Abort transaction")
        if not test:
            transaction.commit()        
        return '\n'.join(out)
